package vip.xiaomoli.courier.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vip.xiaomoli.courier.component.CourierExecutor;
import vip.xiaomoli.courier.dao.CourierDao;
import vip.xiaomoli.courier.model.PageResultForBootstrap;
import vip.xiaomoli.courier.model.TaskInfo;
import vip.xiaomoli.courier.util.CourierConstant;

import java.util.List;

@RestController
@RequestMapping("/courier")
public class CourierController {

    @Autowired
    private CourierDao dao;

    @GetMapping("/taskInfo/page")
    public PageResultForBootstrap pageTaskInfo(int succFlag, int offset, int limit) {
        int total = dao.countTaskInfo(succFlag);
        List<TaskInfo> rows = dao.pageTaskInfo(succFlag, offset, limit);
        return new PageResultForBootstrap(total, rows);
    }

    @GetMapping("/taskInfo/failMessage")
    public String getFailMessage(int succFlag, long id) {
        return dao.getFailMessage(succFlag, id);
    }

    @PostMapping("/taskInfo/execute")
    public void execTaskInfos(@RequestBody List<Long> ids) {
        Thread.currentThread().setName(CourierConstant.THREAD_NAME);
        List<TaskInfo> list = dao.getTaskInfos4Exec(ids);
        for (TaskInfo ti : list) {
            CourierExecutor.execute(ti, dao);
        }
    }

    @GetMapping("/taskInfo/param")
    public String getParam(int succFlag, long id) {
        return dao.getParam(succFlag, id);
    }

    @PostMapping("/taskInfo/param/update")
    public void updateParam(String newData, long id) {
        dao.updateParam(newData, id);
    }

}
